﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>医生排班</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.8.11/dist/css/layui.css">
    <link href="//unpkg.com/layui@2.10.1/dist/css/layui.css" rel="stylesheet">
    <style>
        .layui-container {
            width: 100%;
            overflow-x: auto;
        }

        .layui-table {
            width: auto;
            min-width: 100%;
        }

            .layui-table th, .layui-table td {
                white-space: nowrap;
                text-align: center;
            }

        .day-header {
            text-align: center;
            background-color: #f2f2f2;
        }

        .time-header {
            text-align: center;
        }
    </style>
</head>
<body>

    <button type="button" class="layui-btn layui-btn-normal" id="addBtn">排班设置</button>
    <div class="layui-container">
        <table id="doctorScheduleTable" class="layui-table" lay-filter="doctorScheduleTable">
            <!-- 表头将通过 JavaScript 动态生成 -->
        </table>
    </div>

    <!-- 新增对话框 -->
    <div id="addDialog" style="display: none; padding: 15px; width: 100%;overflow: auto;">
        <form class="layui-form" id="addForm" lay-filter="addForm">
            <table style="width:800px">
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">医生</label>
                            <div class="layui-input-block" style="width:300px">
                                <select name="doctorId" id="doctorId">
                                    <option value="0">请选择</option>
                                </select>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width:100px">日期</label>
                            <div class="layui-input-block">

                                <input type="date" class="layui-input" name="Date" id="ID-laydate-type-datetime" placeholder="请选择时间">

                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">上午号源:</label>
                            <div class="layui-input-block">
                                <input type="text" style="width:300px" id="MorningNumberSources" name="MorningNumberSources" autocomplete="off"
                                       placeholder="请输入" lay-verify="required" class="layui-input">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">下午号源:</label>
                            <div class="layui-input-block">
                                <input type="text" style="width:300px" id="AfternoonNumberSources" name="AfternoonNumberSources" autocomplete="off"
                                       placeholder="请输入" lay-verify="required" class="layui-input">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">上午接诊人数:</label>
                            <div class="layui-input-block">
                                <input type="text" style="width:300px" id="MorningNumberPatients" name="MorningNumberPatients" autocomplete="off"
                                       placeholder="请输入" lay-verify="required" class="layui-input">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">上午接诊人数:</label>
                            <div class="layui-input-block">
                                <input type="text" style="width:300px" id="AfternoonNumberPatients" name="AfternoonNumberPatients" autocomplete="off"
                                       placeholder="请输入" lay-verify="required" class="layui-input">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width:100px">上午是否排班:</label>
                            <div class="layui-input-block">
                                <input type="checkbox" id="MorningIsNo" checked name="MorningIsNo" lay-skin="switch" lay-filter="switchTest" title="开关">
                            </div>
                        </div>
                    </td>
                </tr> 
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width:100px">下午是否排班:</label>
                            <div class="layui-input-block">
                                <input type="checkbox" id="AfternoonIsNo" checked name="AfternoonIsNo" lay-skin="switch" lay-filter="switchTest" title="开关">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width:100px">是否排班:</label>
                            <div class="layui-input-block">
                                <input type="checkbox" id="IsScheduling" checked name="IsScheduling" lay-skin="switch" lay-filter="switchTest" title="开关">
                            </div>
                        </div>
                    </td>
                </tr>
            </table>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="addSubmit">添加</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>

    <script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/layui@2.8.11/dist/layui.js"></script>
    <script type="text/html" id="operationTpl">

         <div class="layui-form-item">
            <button type="button" class="layui-btn layui-btn-normal" id="addBtn">⚙</button>
        </div>
    </script>

    <script>
        
        layui.use(['table', 'jquery', 'layer', 'form'], function () {
            var table = layui.table;
            var $ = layui.jquery;
            var layer = layui.layer;
                  var form = layui.form;
                        var laydate = layui.laydate;
            // 获取本周的日期（周一到周日）
            function getWeekDates() {
                var dates = [];
                var days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
                var today = new Date();
                var dayOfWeek = today.getDay(); // 0是周日，1是周一...
                var diff = today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1); // 调整到本周一

                for (var i = 0; i < 7; i++) {
                    var date = new Date(today.setDate(diff + i));
                    var dayName = days[date.getDay()];
                    var dateStr = date.getFullYear() + '/' +
                        (date.getMonth() + 1) + '/' +
                        date.getDate() + ' ' + dayName;
                    dates.push(dateStr);
                }

                return dates;
            }

            // 构建表头
            function buildTableHeader(dates) {
                var header = '<thead><tr><th rowspan="2">医生姓名</th><th rowspan="2">科室</th>';

                // 添加日期列
                dates.forEach(function (date) {
                    header += '<th colspan="2" class="day-header">' + date + '</th>';
                });

                header += '<th rowspan="2">操作</th></tr><tr>';

                // 添加上下午列
                dates.forEach(function () {
                    header += '<th class="time-header">上午</th><th class="time-header">下午</th>';
                });

                header += '</tr></thead>';
                return header;
            }

            // 从 API 获取医生排班数据
            function fetchDoctorSchedules(dates) {
                    // 添加日期范围参数
                    var params = {
                        startDate: dates[0].split(' ')[0], // 获取日期部分
                        endDate: dates[6].split(' ')[0]
                    };

                    $.ajax({
                        //url: 'https://localhost:7171/api/DoctorScheduling/GetDoctorScheduling',
                        url: `@ViewBag.BaseUrl/T5/DoctorScheduling/GetDoctorScheduling`,
                        type: 'GET',
                        data: params,
                        dataType: 'json',
                        success: function (res) {
                            if (res) {
                                console.log(res);
                                renderTableData(res.list, dates);
                                layer.closeAll('loading');
                            } else {
                                //reject(new Error('API 返回数据不符合预期'));
                                 layer.closeAll('loading');
                                 layer.msg('数据加载失败', { icon: 2 });
                            }
                        },
                        error: function (xhr, status, error) {
                            //reject(new Error('API 请求失败: ' + error.message));
                        }
                    });
            }

            // 渲染表格数据
            function renderTableData(data, dates) {
                var tbody = '<tbody>';

                data.forEach(function (doctor) {
                    tbody += '<tr>';
                    tbody += '<td>' + (doctor.doctorName || '') + '</td>';
                    tbody += '<td>' + (doctor.deparName || '') + '</td>';
                        tbody += '<td>' + (doctor.morningNumberSources0 || '') + '</td>';
                        tbody += '<td>' + (doctor.afternoonNumberSources0 || '') + '</td>';
                        tbody += '<td>' + (doctor.morningNumberSources1 || '') + '</td>';
                        tbody += '<td>' + (doctor.afternoonNumberSources1 || '') + '</td>';
                        tbody += '<td>' + (doctor.morningNumberSources2 || '') + '</td>';
                        tbody += '<td>' + (doctor.afternoonNumberSources2 || '') + '</td>';
                        tbody += '<td>' + (doctor.morningNumberSources3 || '') + '</td>';
                        tbody += '<td>' + (doctor.afternoonNumberSources3 || '') + '</td>';
                        tbody += '<td>' + (doctor.morningNumberSources4 || '') + '</td>';
                        tbody += '<td>' + (doctor.afternoonNumberSources4 || '') + '</td>';
                        tbody += '<td>' + (doctor.morningNumberSources5 || '') + '</td>';
                        tbody += '<td>' + (doctor.afternoonNumberSources5 || '') + '</td>';
                        tbody += '<td>' + (doctor.morningNumberSources6 || '') + '</td>';
                        tbody += '<td>' + (doctor.afternoonNumberSources6 || '') + '</td>';
                    tbody += '<td><a type="button" class="layui-btn layui-btn-normal" id="addBtn">⚙</a></td>';
                    tbody += '</tr>';
                 });

                tbody += '</tbody>';
                $("#doctorScheduleTable").append(tbody);
            }

            // 初始化表格
            function initTable() {
                var dates = getWeekDates();
                var $table = $('#doctorScheduleTable');

                // 构建表头
                $table.html(buildTableHeader(dates));

                // 显示加载中
                layer.load(2);

                // 获取数据并渲染
                fetchDoctorSchedules(dates);

            }
            // 初始化表格
            initTable();





           // 加载医院数据的函数
            function loadCampuses(pageIndex = 1, pageSize = 50) {
                $.ajax({
                    url: `https://localhost:7171/api/Doctor/GetDoctor?PageIndex=${pageIndex}&PageSize=${pageSize}`,
                    success: function (res) {
                        var $select = $('#doctorId');
                        $select.find('option:not(:first)').remove();
                        res.data.forEach(item => {
                            $select.append(`<option value="${item.doctorId}">${item.doctorName}</option>`);
                        });
                        form.render('select');
                    },
                   
                });
            }

            loadCampuses();


            // 新增按钮点击事件
            $('#addBtn').on('click', function () {
                layer.open({
                    type: 1,
                    title: '新增',
                    area: ['60%', '60%'],
                    content: $('#addDialog'),
                    success: function () {
                        // 重置表单
                        $('#addForm')[0].reset();
                        // 初始化日期选择器
                        laydate.render({
                            elem: '#date',
                            trigger: 'click'
                        });
                   
                        form.render();
                    }
                });
            });


                //新增表单提交
                form.on('submit(addSubmit)', function (data) {
                    var formData = data.field;
                    var postData = {
                          DoctorId: formData.doctorId,
                          MorningNumberSources: formData.MorningNumberSources,
                          AfternoonNumberSources: formData.AfternoonNumberSources,
                          MorningNumberPatients: formData.MorningNumberPatients,
                          AfternoonNumberPatients:formData.AfternoonNumberPatients,
                          Date: formData.Date,
                          MorningAdmissions:formData.MorningAdmissions,
                          AfternoonAdmissions:formData.AfternoonAdmissions,
                          MorningIsNo: $("#MorningIsNo").prop('checked'),
                          AfternoonIsNo: $("#AfternoonIsNo").prop('checked'),
                          IsScheduling: $("#IsScheduling").prop('checked'),
                    };

                    layer.load(2);
                    $.ajax({
                        //url: 'https:localhost:7027/api/Message/CreateMessage',
                        url: `https://localhost:7027/api/DoctorScheduling/AddDoctorScheduling`,
                         //url: `@ViewBag.BaseUrl/T6/DoctorScheduling/AddDoctorScheduling`,
                        type: 'post',
                        contentType: 'application/json',
                        data: JSON.stringify(postData),
                        dataType: 'json',
                        success: function (res) {
                            layer.closeAll('loading');
                            if (res.code == 100) {
                                layer.alert(res.test, {
                                    title: '操作成功',
                                    icon: 1,
                                    btn:['确定'],
                                    yes: function (index, layero) {
                                        document.getElementById("addForm").reset();
                                        form.render();
                                        layer.close(index);
                                        layer.closeAll(); 关闭所有弹层
                                         initTable(); 刷新表格数据
                                    }
                                });
                            } else {
                                layer.alert(res.test, {
                                    title: '操作失败',
                                    icon: 2
                                });
                            }
                        },
                        error: function (xhr, status, error) {
                            layer.closeAll('loading');
                            layer.alert('请求失败: ' + error, {
                                title: '错误',
                                icon: 2,
                                btn: ['确定']
                            });
                            console.error('AJAX请求失败:', status, error);
                            console.error('响应内容:', xhr.responseText);
                        }
                    });
                    return false;
                });

            });










    </script>
</body>
</html>